﻿var zoomLevelPixelWidth = {"portrait": 16, "landscape": 28};

var map, localControl, zoomLevelCtrl, mapTypeCtrl, delMarkerCtrl, processCtrl, directions;
var zoom4Ctrl, zoom8Ctrl, zoom12Ctrl, zoom16Ctrl, oInterval;
var localResult = {};
var waypoints = {
	'a': '',
	'b': '',
	'markers': {},
	currentIndex: function() {
		return (waypoints.a == '' ? 'a' : 'b');
	},
	contains: function(val) {
		return waypoints.a == val || waypoints.b == val;
	},
	points: function() {
		return (waypoints.isReverseDirection) ? [waypoints.b, waypoints.a] : [waypoints.a, waypoints.b];
	},
	isReverseDirection: false,
	resetDirection: function() {
		waypoints.isReverseDirection = false;
	},
	reset: function() {
		waypoints.a = '';
		waypoints.b = '';
		waypoints.resetDirection();
		delMarkerCtrl.minimize();
		processCtrl.minimize();
	}
};
var isZoomOut = false;

function magnifyMap() {
	if (isZoomOut) {
		map.returnToSavedPosition();
	} else {
		map.savePosition();
		map.setCenter(localResult.point, 15);
		map.updateInfoWindow();
	}
	isZoomOut = !isZoomOut;
}

function pinThis(ll) {
	localControl.goIdle();

	if (!waypoints.contains(ll)) {
		var index = waypoints.currentIndex();
		waypoints[index] = ll;

		if (index == 'b') {
			processCtrl.maximize();
		}

		if (waypoints.markers[index]) {
			map.removeOverlay(waypoints.markers[index]);

			if (directions.getNumRoutes() != 0) {
				directions.clear();
				waypoints.markers['a'].show();
			}
		}

		waypoints.markers[index] = new GMarker(localResult.point);
		var marker = waypoints.markers[index];
		var html = localResult.html;
		GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowHtml('<div class="gmls-result-wrapper">' + html + '</div>');
		});
		map.addOverlay(marker);
		waypoints.resetDirection();
		marker.setImage('http://maps.google.com/mapfiles/marker_green' + index.toUpperCase() + '.png');
		delMarkerCtrl.maximize();
	}
}

function loading() {
	var i = 0;
	oInterval = setInterval(function() {
		var opc = i % 10 / 10;
		zoom16Ctrl.getContainer().style.opacity = opc % 1;
		zoom12Ctrl.getContainer().style.opacity = (opc + 0.2) % 1;
		zoom8Ctrl.getContainer().style.opacity = (opc + 0.4) % 1;
		zoom4Ctrl.getContainer().style.opacity = (opc + 0.8) % 1;
		i++;
	}, 200);
}

function loaded() {
	clearInterval(oInterval);
	zoom4Ctrl.getContainer().style.opacity = 1;
	zoom8Ctrl.getContainer().style.opacity = 1;
	zoom12Ctrl.getContainer().style.opacity = 1;
	zoom16Ctrl.getContainer().style.opacity = 1;
}

function initialize() {
	if (GBrowserIsCompatible()) {
		function M8Control(ctrlClass, clickFunc) {
			this.ctrlClass = ctrlClass;
			this.clickFunc = clickFunc;
		}

		M8Control.prototype = new GControl();

		M8Control.prototype.initialize = function(map) {
			var container = document.createElement("div");
			container.className = this.ctrlClass;
			this._container = container;
			GEvent.addDomListener(container, "click", this.clickFunc);

			map.getContainer().appendChild(container);
			return container;
		};

		M8Control.prototype.getDefaultPosition = function() {
			return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(0, 0));
		};

		M8Control.prototype.getContainer = function() {
			return this._container;
		};

		M8Control.prototype.minimize = function() {
			this._container.style.height = '1px';
			this._container.style.width = '1px';
		};

		M8Control.prototype.maximize = function() {
			this._container.style.height = '64px';
			this._container.style.width = '64px';
		};

		var container = document.getElementById("map");
		var orientation = container.getAttribute("orientation");
		var isNormalMap = true;

		var zoom = parseInt(container.getAttribute("zoom"));
		var latlng = GLatLng.fromUrlValue(container.getAttribute("center"));

		map = new GMap2(container);
		directions = new GDirections(map);

		GEvent.addListener(directions, "load", function() {
			GEvent.addListener(directions.getMarker(0), "click", function() {
				directions.getMarker(0).showMapBlowup();
			});
			GEvent.addListener(directions.getMarker(1), "click", function() {
				directions.getMarker(1).showMapBlowup();
			});
		});

		zoomLevelCtrl = new M8Control("zoomLevelCtrl", function() {
			alert("当前放大级别为：" + map.getZoom());
		});
		zoom4Ctrl = new M8Control("zoom4Ctrl", function() {
			map.setZoom(4);
		});
		zoom8Ctrl = new M8Control("zoom8Ctrl", function() {
			map.setZoom(8);
		});
		zoom12Ctrl = new M8Control("zoom12Ctrl", function() {
			map.setZoom(12);
		});
		zoom16Ctrl = new M8Control("zoom16Ctrl", function() {
			map.setZoom(16);
		});

		delMarkerCtrl = new M8Control("delMarkerCtrl", function() {
			if (!localControl.idle) {
				localControl.goIdle();
				delMarkerCtrl.minimize();
				return;
			}

			if (directions.getNumRoutes() == 0) {
				map.clearOverlays();
				waypoints.reset();
			} else {
				directions.clear();
				waypoints.resetDirection();
				waypoints.markers['a'].show();
				waypoints.markers['b'].show();
			}
		});

		processCtrl = new M8Control("processCtrl", function() {
			waypoints.markers['a'].hide();
			waypoints.markers['b'].hide();
			directions.clear();
			directions.loadFromWaypoints(waypoints.points(), {
				getSteps: false,
				preserveViewport: false});

			waypoints.isReverseDirection = !waypoints.isReverseDirection;
		});

		map.addControl(zoomLevelCtrl, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(80, 0)));
		map.addControl(zoom4Ctrl, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(48 + zoomLevelPixelWidth[orientation] * 4, 5)));
		map.addControl(zoom8Ctrl, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(48 + zoomLevelPixelWidth[orientation] * 8, 5)));
		map.addControl(zoom12Ctrl, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(48 + zoomLevelPixelWidth[orientation] * 12, 5)));
		map.addControl(zoom16Ctrl, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(48 + zoomLevelPixelWidth[orientation] * 16, 5)));

		GEvent.addListener(map, "zoomend", function(oldLevel, newLevel) {
			zoomLevelCtrl.getContainer().style.width = (newLevel * zoomLevelPixelWidth[orientation]) + 'px';
		});

		map.addControl(new M8Control("zoomInCtrl", function() {
			map.zoomIn();
		}), new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(0, 5)));

		map.addControl(new M8Control("zoomOutCtrl", function() {
			map.zoomOut();
		}), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(0, 5)));


		mapTypeCtrl = new M8Control("mapTypeCtrl", function() {
			map.setMapType(isNormalMap ? G_SATELLITE_MAP : G_NORMAL_MAP);
			isNormalMap = !isNormalMap;
		});

		map.addControl(mapTypeCtrl, new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(0, 30)));

		if (google.loader.ClientLocation) {
			zoom = 13;
			latlng = new GLatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude);
		}

		GEvent.addListener(map, "load", function() {
			zoomLevelCtrl.getContainer().style.width = (map.getZoom() * zoomLevelPixelWidth[orientation]) + 'px';
		});
		map.setCenter(latlng, zoom);

		function genInfoWindowHtml(marker, html, result) {
			localResult.point = marker.getPoint();
			var dom = document.createElement("div");
			var ll = marker.getPoint().lat() + "," + marker.getPoint().lng();
			var staticUrl = "http://maps.google.com/staticmap?center="+ll+"&zoom=15&size=220x120&markers="+ll+",green" + waypoints.currentIndex() + "&key=ABQIAAAAxeA5H8HrULf2I9CaEu7XaBRgMWdz6d5JelwwaJzSDwr7Dxoa4BTg2lkRvO0_ootPf1lgTJumIJZwlg";
			var s = '<div style="width: 220px;">' + '<p>' + result.title + '</p>';
			if (result.streetAddress) {
				s += result.streetAddress + '<br/>';
			}

			if (result.phoneNumbers) {
				s += result.phoneNumbers[0].number + '<br/>';
			}
			s += '<img style="display: block;" border="1" height="120" width="220" src="' + staticUrl + '" onclick="magnifyMap();" usemap="#pinThis"/><br/>';
			s += '<map name="pinThis"><area shape="circle" coords="110,60,32" href="javascript:pinThis(\'' + ll + '\');"/></map>';
			s += '</div>';
			dom.innerHTML = s;
			localResult.html = s;
			return dom;
		}
		function searchCompleteCallback() {
			delMarkerCtrl.maximize();
			loaded();
		}
		localControl = new google.maps.LocalSearch({
				suppressZoomToBounds: true,
				onSearchCompleteCallback: searchCompleteCallback,
				onGenerateMarkerHtmlCallback: genInfoWindowHtml
			});

		map.addControl(new M8Control("searchCtrl", function() {
			var key = prompt('请输入查询地址', '');
			if (key != undefined && key != '') {
				localControl.execute(key);
				loading();
			}
		}), new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(0, 30)));

		map.addControl(processCtrl, new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(80, 30)));
		map.addControl(delMarkerCtrl, new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(0, 110)));
		map.addControl(localControl, new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(70, 30)));

		GEvent.addListener(map, "click", function(overlay, latlng) {
			map.panTo(latlng);
		});
	}
}

GSearch.setOnLoadCallback(initialize);